package com.stx.jeepay.core.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.stx.jeepay.core.dao.PayOrderDao;
import com.stx.jeepay.core.dao.PayOrderDivisionRecordDao;
import com.stx.jeepay.core.entity.PayOrderDivisionRecordEntity;
import com.stx.jeepay.core.entity.PayOrderEntity;
import com.stx.jeepay.core.expection.BizException;
import com.stx.jeepay.core.service.PayOrderDivisionRecordService;
import com.stx.jeepay.core.utils.SeqKit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;


@Service("payOrderDivisionRecordService")
public class PayOrderDivisionRecordServiceImpl extends ServiceImpl<PayOrderDivisionRecordDao, PayOrderDivisionRecordEntity> implements PayOrderDivisionRecordService {

    @Autowired
    private PayOrderDao payOrderDao;

    /**
     * 更新分账记录为分账成功
     **/
    @Override
    public void updateRecordSuccessOrFail(List<PayOrderDivisionRecordEntity> records, Byte state, String channelBatchOrderId, String channelRespResult) {
        if (records == null || records.isEmpty()) {
            return;
        }

        List<Long> recordIds = new ArrayList<>();
        records.stream().forEach(i -> recordIds.add(i.getRecordId()));

        PayOrderDivisionRecordEntity updateRecord = new PayOrderDivisionRecordEntity();
        updateRecord.setState(state);
        updateRecord.setChannelBatchOrderId(channelBatchOrderId);
        updateRecord.setChannelRespResult(channelRespResult);
        update(updateRecord, new LambdaQueryWrapper<PayOrderDivisionRecordEntity>()
                .in(PayOrderDivisionRecordEntity::getRecordId, recordIds)
                .eq(PayOrderDivisionRecordEntity::getState, PayOrderDivisionRecordEntity.STATE_WAIT));
    }

    /**
     * 更新分账记录为分账成功  ( 单条 )  将：  已受理 更新为： 其他状态
     **/
    @Override
    public void updateRecordSuccessOrFailBySingleItem(Long recordId, Byte state, String channelRespResult) {
        PayOrderDivisionRecordEntity updateRecord = new PayOrderDivisionRecordEntity();
        updateRecord.setState(state);
        updateRecord.setChannelRespResult(state == PayOrderDivisionRecordEntity.STATE_SUCCESS ? "" : channelRespResult); // 若明确成功，清空错误信息。
        update(updateRecord, new LambdaQueryWrapper<PayOrderDivisionRecordEntity>()
                .eq(PayOrderDivisionRecordEntity::getRecordId, recordId)
                .eq(PayOrderDivisionRecordEntity::getState, PayOrderDivisionRecordEntity.STATE_ACCEPT));
    }

    /**
     * 更新分账订单为： 等待分账中的状态
     **/
    @Transactional
    @Override
    public void updateResendState(String payOrderId) {
        PayOrderEntity updateRecord = new PayOrderEntity();
        updateRecord.setDivisionState(PayOrderEntity.DIVISION_STATE_WAIT_TASK);

        // 更新订单
        int update = payOrderDao.update(updateRecord, new LambdaQueryWrapper<PayOrderEntity>()
                .eq(PayOrderEntity::getPayOrderId, payOrderId)
                .eq(PayOrderEntity::getDivisionState, PayOrderEntity.DIVISION_STATE_FINISH));

        if (update <= 0) {
            throw new BizException("更新订单分账状态失败");
        }

        PayOrderDivisionRecordEntity updateRecordByDiv = new PayOrderDivisionRecordEntity();
        updateRecordByDiv.setBatchOrderId(SeqKit.genDivisionBatchId()); // 重新生成batchOrderId, 避免部分失败导致： out_trade_no重复。
        updateRecordByDiv.setState(PayOrderDivisionRecordEntity.STATE_WAIT); //待分账
        updateRecordByDiv.setChannelRespResult("");
        updateRecordByDiv.setChannelBatchOrderId("");

        boolean result = update(updateRecordByDiv, new LambdaQueryWrapper<PayOrderDivisionRecordEntity>()
                .eq(PayOrderDivisionRecordEntity::getPayOrderId, payOrderId)
                .eq(PayOrderDivisionRecordEntity::getState, PayOrderDivisionRecordEntity.STATE_FAIL));

        if (!result) {
            throw new BizException("更新分账记录状态失败");
        }
    }
}